package com.hwy.catering.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwy.catering.dto.CategoryDto;
import com.hwy.catering.entity.Category;
import com.hwy.catering.entity.Dish;
import com.hwy.catering.entity.FlavorDetail;
import com.hwy.catering.entity.Meal;
import com.hwy.catering.mapper.CategoryMapper;
import com.hwy.catering.mapper.DishMapper;
import com.hwy.catering.mapper.MealDetailMapper;
import com.hwy.catering.mapper.MealMapper;
import com.hwy.catering.service.CategoryService;
import com.hwy.catering.utils.R;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hwy.catering.utils.ConstantPool.CATEGORY_ALL_KEY;
import static com.hwy.catering.utils.ConstantPool.CATEGORY_ALL_KEY_TTL;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private DishMapper dishMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MealDetailMapper mealDetailMapper;

    @Resource
    private MealMapper mealMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public R findDetailCategory(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> eq = wrapper.eq(Category::getType, type);
        List<Category> categories = categoryMapper.selectList(eq);
        ArrayList<Object> list = new ArrayList<>();
        for (Category category:categories) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("value", category.getId().toString());
            map.put("label", category.getName());
            list.add(map);
        }
        return R.success(list);
    }

    @Override
    public R deleteCategory(CategoryDto categoryDto) {
        //判断菜品是否有用到该类别
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Meal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryDto.getId());
        wrapper1.eq(Meal::getCategoryId,categoryDto.getId());
        Integer count = dishMapper.selectCount(wrapper);
        Integer integer = mealMapper.selectCount(wrapper1);
        //该类别没有被关联，则可以删除
        if (count == 0 && integer == 0 ){
            //如果没有子节点，就是单个删除
            if (categoryDto.getChildren().size() == 0){
                categoryMapper.deleteById(categoryDto.getId());
            } else { //有子节点就是批量删除
                //该队列存放要删除的数据id
                ArrayList<Long> list = new ArrayList<>();
                List<CategoryDto> children = categoryDto.getChildren();
                for (CategoryDto categoryDto1 :children) {
                    //将id存入队列
                    list.add(categoryDto1.getId());
                }
                categoryMapper.deleteBatchIds(list);
            }
        }else {//菜品关联了该类别，不能删除
            return R.error("该类别已经被关联，不能删除。");
        }

        return R.success("类别删除成功。");
    }

    @Override
    public R addCategory(Category category) {
        categoryMapper.insert(category);
        return R.success("类别添加成功。");
    }

    @Override
    public R findCategory() {
        //最终返回列表
        ArrayList<Object> finaList = new ArrayList<>();
//        if (stringRedisTemplate.opsForHash().get(CATEGORY_ALL_KEY,CATEGORY_ALL_KEY) == null){
            //树状控件的根节点（第一层）
            CategoryDto categoryDto = new CategoryDto();
            List<Category> categories = categoryMapper.selectList(null);
            categoryDto.setId(0L);
            categoryDto.setLabel("分类列表");
            //根节点的下一层节点（第二层）的菜品分类
            CategoryDto dishCategory = new CategoryDto();
            dishCategory.setId(1L);
            dishCategory.setLabel("菜品分类");
            //根节点的下一层节点（第二层）的套餐分类
            CategoryDto mealCategory = new CategoryDto();
            mealCategory.setId(2L);
            mealCategory.setLabel("套餐分类");

            ArrayList<CategoryDto> categoryList = new ArrayList<>();
            ArrayList<CategoryDto> dishList = new ArrayList<>();
            ArrayList<CategoryDto> mealList = new ArrayList<>();
            for (Category category : categories) {
                //如果是菜品,存入三层。（第三层）
                if (category.getType() == 1){
                    CategoryDto categoryDto1 = new CategoryDto();
                    categoryDto1.setId(category.getId());
                    categoryDto1.setLabel(category.getName());
                    dishList.add(categoryDto1);
                } else { //如果是套餐,存入三层。（第三层）
                    CategoryDto categoryDto2 = new CategoryDto();
                    categoryDto2.setId(category.getId());
                    categoryDto2.setLabel(category.getName());
                    mealList.add(categoryDto2);
                }
            }
            dishCategory.setChildren(dishList);
            mealCategory.setChildren(mealList);
            categoryList.add(dishCategory);
            categoryList.add(mealCategory);
            categoryDto.setChildren(categoryList);
            finaList.add(categoryDto);

            //List转Json
//            String s = JSON.toJSONString(categoryDto);
//            redisTemplate.opsForHash().put(CATEGORY_ALL_KEY,CATEGORY_ALL_KEY,categoryDto);
//            redisTemplate.expire(CATEGORY_ALL_KEY,CATEGORY_ALL_KEY_TTL,TimeUnit.MINUTES);
//        }else {
//            Object o = redisTemplate.opsForHash().get(CATEGORY_ALL_KEY, CATEGORY_ALL_KEY);
//            System.out.println("object:"+o.toString());
////            CategoryDto categoryDto = JSON.parseObject(o, CategoryDto.class);
//            finaList.add(o.toString());
//            return R.success(finaList);
//        }
        return R.success(finaList);
    }
}
